package com.TPNexus.dao;

import java.util.ArrayList;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import org.hibernate.Session;
import com.TPNexus.model.Product;
import java.io.Serializable;

@Named
@ApplicationScoped
public class ProductDAO implements Serializable {

	private static final long serialVersionUID = 1L;
	private Session session=HibernateInitial.getSession();
	public ArrayList<Product> getProductList() {
		session.beginTransaction();
		ArrayList<Product> list = (ArrayList<Product>) session.createQuery(
				"from Product p where p.status=true").list();

		for (Product product : list) {
			System.out.println(product.getName());
		}

		session.getTransaction().commit();
		// HibernateUtil.getSessionFactory().close(); //(in web app why can not
		// close the factory?)
		return list;
	}

	public int addNewProduct(Product product) throws Exception {
		int result;
		try {
			session.beginTransaction();
			session.save(product);
			session.getTransaction().commit();
			result = 1;
		} catch (RuntimeException e) {
			session.getTransaction().rollback();
			System.out.println(e.toString());
			result = 0;
			throw e;
		}
		return result;
	}

	public int deleteProduct(Product product) {
		int result;
		try {
			session.beginTransaction();
			product.setStatus(false);
			session.update(product);
			session.getTransaction().commit();
			result = 1;
		} catch (RuntimeException e) {
			session.getTransaction().rollback();
			System.out.println(e.toString());
			result = 0;
			throw e;
		}
		return result;
	}

	public Product getProductDetail(long id) {
		Product result;
		try {
			session.beginTransaction();
			result = (Product) session.get(Product.class, id);
			session.getTransaction().commit();
		} catch (RuntimeException e) {
			session.getTransaction().rollback();
			System.out.println(e.toString());
			throw e;
		}
		return result;
	}

	public int updateProduct(Product product) {

		int result;

		try {
			session.beginTransaction();
			session.update(product);
			session.getTransaction().commit();
			result = 1;
		} catch (RuntimeException e) {
			session.getTransaction().rollback();
			System.out.println(e.toString());
			result = 0;
			throw e;
		}
		return result;
	}
}
